package com.zx.mes.hyl.send;


import com.zx.mes.hyl.properties.RabbitmqExchangeAndQueueProperties;
import com.zx.mes.hyl.properties.RabbitmqProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 消息发送配置
 * @author huayunlong
 * @date 2018-8-6
 */
@Component
@Slf4j
public class RabbitSender implements InitializingBean{

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitmqProperties rabbitmqProperties;



    final RabbitTemplate.ReturnCallback returnCallback = (message, replyCode, replyText, exchange, routingKey) -> {
        log.debug("ReturnCallback==>  message:[{}]  ,replyCode:[{}]  ,replyText:[{}]  ,exchange:[{}]  ,routingKey:[{}]"
                ,message, replyCode, replyText, exchange, routingKey);
    };

    final RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) -> {
        log.debug("ConfirmCallback==>  correlationData:[{}], ack:[{}],, cause:[{}]",correlationData, ack, cause);
    };

    public void sender(Object object,String exchange,String key){
        this.rabbitTemplate.setReturnCallback(returnCallback);
        this.rabbitTemplate.setConfirmCallback(confirmCallback);

        this.rabbitTemplate.convertAndSend(exchange
                ,key,object,new CorrelationData(UUID.randomUUID().toString()));
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        /// 这样写被覆盖了
        RabbitmqExchangeAndQueueProperties[] exchangeAndQueueProperties = this.rabbitmqProperties.getExchangeAndQueueProperties();
        for (int i = 0; i <exchangeAndQueueProperties.length ; i++) {
            this.rabbitTemplate.setExchange(exchangeAndQueueProperties[i].getExchangeProperties().getExchange());
            this.rabbitTemplate.setQueue(exchangeAndQueueProperties[i].getQueueProperties()[0].getQueue());
            this.rabbitTemplate.setRoutingKey(exchangeAndQueueProperties[i].getQueueProperties()[0].getKey());
        }
    }

//    public void senderOrder(Order order){
//        this.rabbitTemplate.setReturnCallback(returnCallback);
//        this.rabbitTemplate.setConfirmCallback(confirmCallback);
//
//        this.rabbitTemplate.convertAndSend("test.exchange"
//                ,"test.send",order,new CorrelationData(UUID.randomUUID().toString()));
//    }
}
